package com.lvyq.myplayer.ui.activity.history

import android.content.Intent
import android.widget.CheckBox
import android.widget.ImageButton
import androidx.activity.viewModels
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.widget.Toolbar
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.lvyq.myplayer.R
import com.lvyq.myplayer.adapter.current.CurrentPlayLstAdapter
import com.lvyq.myplayer.adapter.history.PlayOperateAdapter
import com.lvyq.myplayer.base.BaseActivity
import com.lvyq.myplayer.common.shared.MainAudioSharedPrefsManager
import com.lvyq.myplayer.database.PlayerDatabase
import com.lvyq.myplayer.model.history.PlayHistoryEntity
import com.lvyq.myplayer.model.history.PlayHistoryViewModel
import com.lvyq.myplayer.model.history.PlayHistoryViewModelFactory
import com.lvyq.myplayer.service.AudioService
import com.lvyq.myplayer.util.ToolBarManager
import kotlinx.coroutines.launch

/**
 * 文件描述：UserCenterActivity
 * 作者：lvyq
 * 创建时间：2025-06-18
 * 修改时间：2025-06-18
 */
class ItemBatchActivity : BaseActivity(),ToolBarManager{
    private val playHistoryViewModel: PlayHistoryViewModel by viewModels {
        PlayHistoryViewModelFactory(PlayerDatabase.getDatabase(this).playHistoryDao())
    }

    override val toolbar by lazy { findViewById<Toolbar>(R.id.toolBar) }

    lateinit var rvHistoryView:RecyclerView

    lateinit var  playOperateAdapter:PlayOperateAdapter

    override var currentPlayAdapter: CurrentPlayLstAdapter? = null


    override fun getLayoutId(): Int {
        return  R.layout.activity_play_operate
    }

    override fun initData() {
        initPlayBoxService()

        initSettingToolBar("未选择")
        enableBackButton()

        rvHistoryView=findViewById(R.id.rvHistoryView)
        rvHistoryView.layoutManager=LinearLayoutManager(this)

        playOperateAdapter= PlayOperateAdapter(object :PlayOperateAdapter.OnSelectionChangeListener{
            override fun onSelectionChanged(selectedCount: Int) {
                initSettingToolBar("已选择"+selectedCount+"个")
            }

        })

        lifecycleScope.launch {
            var allPlayHistoryListFlow = playHistoryViewModel.getAllPlayHistoryListFlow(1)
            allPlayHistoryListFlow.collect{ lst->
                var list= ArrayList<PlayHistoryEntity>()
                lst.forEach {data->
                    list.add(data)

                }
                playOperateAdapter.initData(list)
            }
        }
        rvHistoryView.adapter=playOperateAdapter
    }

    override fun initListener() {
        super.initListener()
        // 全选CheckBox监听
        findViewById<CheckBox>(R.id.cb_select_all).apply {
            setOnCheckedChangeListener { _, isChecked ->
                if (isChecked) {
                    playOperateAdapter.selectAll()
                } else {
                    playOperateAdapter.clearSelections()
                }
            }
        }

        // 删除按钮监听
        findViewById<ImageButton>(R.id.btn_delete).setOnClickListener {
            val selectedItems = playOperateAdapter.getSelectedItems()
            if (selectedItems?.isEmpty() == true) {
                myToast("请选择要删除的条目")
                return@setOnClickListener
            }

            AlertDialog.Builder(this)
                .setTitle("删除确认")
                .setMessage("确定要删除选中的${selectedItems?.size}项吗？")
                .setPositiveButton("删除") { _, _ ->
                    lifecycleScope.launch {
                        // 批量删除
                        selectedItems?.let { it1 -> playHistoryViewModel.deletePlayHistoryByIds(it1.map { it.id }) }

                        // 刷新数据
                        playOperateAdapter?.clearSelections()
                        findViewById<CheckBox>(R.id.cb_select_all).isChecked = false
                    }
                }
                .setNegativeButton("取消", null)
                .show()
        }




    }
    /**
     * 播放栏服务初始化
     */
    private fun initPlayBoxService() {
        initMainPlayBoxListener()
        currentPlayAdapter=getCurrentPlayLstAdapter()
        initAudioPlayLst(this)

        //设置viewpage2 适配器
        recreateViewPagerAdapter()
        initMainPlayStateChangeUI()
        // updateMainPlayStateBtn(false)
        var songInfo = MainAudioSharedPrefsManager.getSongInfo(this)
        var currentAudioPosition = MainAudioSharedPrefsManager.getCurrentAudioPosition(this)
        //通过audioservice 播放,混合启动，保证退出当前页仍然播放
        val audioIntent = Intent(this, AudioService::class.java)
        //传递值到AudioService中
        audioIntent.putExtra("data",songInfo)
        audioIntent.putExtra("from",-1)
        audioIntent.putExtra("position",currentAudioPosition?.toInt())
        //绑定 BIND_AUTO_CREATE 服务未创建时创建并绑定
        bindService(audioIntent,connection, BIND_AUTO_CREATE)
        //启动
        startService(audioIntent)
    }

    private fun getCurrentPlayLstAdapter(): CurrentPlayLstAdapter {
        return CurrentPlayLstAdapter(this)
    }

    override fun onDestroy() {
        super.onDestroy()
    }

}






